/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.cspimp.psp.domain.TrainExamination;
import me.zhengjie.modules.cspimp.psp.domain.TrainExaminationMember;
import me.zhengjie.modules.cspimp.psp.domain.vo.TrainExaminationVo;
import me.zhengjie.modules.cspimp.psp.repository.TrainExaminationMemberRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.TrainExaminationRepository;
import me.zhengjie.modules.cspimp.psp.service.TrainExaminationService;
import me.zhengjie.modules.cspimp.psp.service.dto.TrainExaminationDto;
import me.zhengjie.modules.cspimp.psp.service.dto.TrainExaminationQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.TrainExaminationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-30
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TrainExaminationServiceImpl implements TrainExaminationService {

    private final TrainExaminationRepository trainExaminationRepository;
    private final TrainExaminationMapper trainExaminationMapper;
    private final TrainExaminationMemberRepository trainExaminationMemberRepository;
    private final UserRepository userRepository;


    @Override
    public Map<String, Object> queryAll(TrainExaminationQueryCriteria criteria, Pageable pageable) {
        Page<TrainExamination> page = trainExaminationRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(trainExaminationMapper::toDto));
    }

    @Override
    public List<TrainExaminationDto> queryAll(TrainExaminationQueryCriteria criteria) {
        return trainExaminationMapper.toDto(trainExaminationRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public TrainExaminationDto findById(Long id) {
        TrainExamination trainExamination = trainExaminationRepository.findById(id).orElseGet(TrainExamination::new);
        ValidationUtil.isNull(trainExamination.getId(), "TrainExamination", "id", id);
        return trainExaminationMapper.toDto(trainExamination);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TrainExaminationDto create(TrainExaminationVo resources) {
        TrainExamination trainExamination = new TrainExamination();
        BeanUtils.copyProperties(resources, trainExamination);
        trainExamination.setCid(0L);
        Set<Long> userIds = resources.getExaminationMemberIds();
        if (CollectionUtils.isEmpty(userIds)) {
            throw new BadRequestException("考试人员不能为空");
        }
        trainExaminationRepository.save(trainExamination);
        for (Long userId : userIds) {
            TrainExaminationMember trainExaminationMember = new TrainExaminationMember();
            trainExaminationMember.setExaminationId(trainExamination.getId());
            trainExaminationMember.setUserId(userId);
            trainExaminationMemberRepository.save(trainExaminationMember);

        }
        return trainExaminationMapper.toDto(trainExamination);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TrainExaminationVo resources) {
        TrainExamination trainExamination = trainExaminationRepository.findById(resources.getId()).orElseGet(TrainExamination::new);
        ValidationUtil.isNull(trainExamination.getId(), "TrainExamination", "id", resources.getId());
        BeanUtils.copyProperties(resources, trainExamination);
        //删除之前的人员
        trainExaminationMemberRepository.deleteByExaminationId(resources.getId());
        //新增
        if (!CollectionUtils.isEmpty(resources.getExaminationMemberIds())) {
            for (Long id : resources.getExaminationMemberIds()) {
                TrainExaminationMember trainExaminationMember = new TrainExaminationMember();
                trainExaminationMember.setUserId(id);
                trainExaminationMember.setExaminationId(resources.getId());
                trainExaminationMemberRepository.save(trainExaminationMember);
            }
        }
        trainExaminationRepository.save(trainExamination);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            trainExaminationRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TrainExaminationDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TrainExaminationDto trainExamination : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建时间", trainExamination.getCreateTime());
            map.put("更新时间", trainExamination.getUpdateTime());
            map.put("创建者", trainExamination.getCreateBy());
            map.put("更新者", trainExamination.getUpdateBy());
            map.put("标题", trainExamination.getTitle());
            map.put("开始日期", trainExamination.getStartDate());
            map.put("结束日期", trainExamination.getEndDate());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}